# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import logging

from odoo import api, fields, models, _
from odoo.exceptions import UserError, ValidationError
import math


class StockRuleExt(models.Model):
    _inherit = 'stock.rule'

    @api.model
    def _run_manufacture(self, procurements):
        #logging.info(procurements)
        n_procurements = []
        logging.info("procurements:")
        logging.info(procurements)

        for p in procurements:
            procure = p[0]
            logging.info(procure)
            product = procure.product_id.product_tmpl_id
            origin = procure.origin

            logging.info('origin = '+origin)

            gid = procure.values.get("group_id")
            if not gid:
                procure.values['group_id'] = self.env['procurement.group'].create({
                        'name': origin,
                        'move_type': "direct"
                    })
            logging.info(procure)
            value_pnl = 1
            if product.value_pnl > 0:
                value_pnl = product.value_pnl
            value_set = 1
            if product.value_set > 0:
                value_set = product.value_set
            # if product.opt_lot_size == 0:
            #     raise ValidationError(_('请到产品处维护最佳批量'))
            # 先判断生产数量
            scrap_rate = product.scrap_rate
            p1 = self.env['mrp.production'].search([('name', '=', origin),], limit=1, order='id desc') #('mo_type', '=', 'N'),
            if p1:
                scrap_rate = 0

            opt_lot_size = product.opt_lot_size
            if opt_lot_size == 0:
                opt_lot_size = 1000000
            opt_lot_size_pcs = opt_lot_size * product.value_pnl
            qty_pcs = math.ceil(procure.product_qty / (1 - scrap_rate / 100)) #考虑报废率，计算实际需要投产的数量

            product_qty = math.ceil(qty_pcs / value_pnl) * value_pnl
            p = (p[0]._replace(product_qty=product_qty), p[1])

            # 判断是否大于最佳批量，如果大于就拆分
            if product_qty > opt_lot_size_pcs:
                mo_qty = math.ceil(product_qty / opt_lot_size_pcs)
                tot = product_qty
                for i in range(0, mo_qty-1):
                    todo = opt_lot_size_pcs
                    tot = tot - todo
                    g_name = p[0].values['group_id'].name +'-'+str(i).zfill(3)
                    group_n = self.env['procurement.group'].create({
                        'name': g_name,
                        'move_type': p[0].values['group_id'].move_type,
                        'sale_id': p[0].values['group_id'].sale_id.id,
                        'partner_id': p[0].values['group_id'].partner_id.id,
                    })
                    values = p[0].values.copy()
                    values['group_id'] = group_n
                    procurement_g = self.env['procurement.group'].Procurement(p[0].product_id, todo,
                                                                              p[0].product_uom,
                                                                              p[0].location_id, p[0].name,p[0].origin,
                                                                              p[0].company_id,
                                                                              values)
                    logging.info("p[1]")
                    logging.info(p[1])
                    n_procurements.append((procurement_g, p[1]))
                if tot > 0:
                    g_name = p[0].values['group_id'].name + '-' + str(mo_qty).zfill(3)
                    group_n = self.env['procurement.group'].create({
                        'name': g_name,
                        'move_type': p[0].values['group_id'].move_type,
                        'sale_id': p[0].values['group_id'].sale_id.id,
                        'partner_id': p[0].values['group_id'].partner_id.id,
                    })
                    values = p[0].values.copy()
                    values['group_id'] = group_n
                    procurement_g = self.env['procurement.group'].Procurement(p[0].product_id, tot,
                                                                              p[0].product_uom,
                                                                              p[0].location_id, p[0].name, p[0].origin,
                                                                              p[0].company_id,
                                                                              values)
                    n_procurements.append((procurement_g, p[1]))

            else:
                n_procurements.append(p)
        logging.info("n_procurements:")
        logging.info(n_procurements)
        res = super(StockRuleExt, self)._run_manufacture(procurements=n_procurements)
        return res